package com.easy.app.controller.system;

import com.easy.framework.common.model.R;
import com.easy.framework.database.page.Pagination;
import com.easy.framework.poi.utils.ExcelUtils;
import com.easy.framework.web.base.BaseController;
import com.easy.module.log.annotation.Log;
import com.easy.module.log.entity.SysLoginLog;
import com.easy.module.log.enums.Operation;
import com.easy.module.log.query.SysLoginLogQuery;
import com.easy.module.log.service.ISysLoginLogService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * 系统访问记录
 *
 * @author Easy
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/log/login")
public class SysLoginLogController extends BaseController {

    private final ISysLoginLogService sysLoginLogService;

    @PreAuthorize("@perm.hasPermission('login:log$list')")
    @GetMapping("/page")
    public R<Pagination<SysLoginLog>> page(SysLoginLogQuery query) {
        return R.success(sysLoginLogService.page(query, () -> sysLoginLogService.queryList(query)));
    }

    @Log(title = "登录日志", type = Operation.EXPORT)
    @PreAuthorize("@perm.hasPermission('login:log$export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysLoginLogQuery query) throws IOException {
        List<SysLoginLog> list = sysLoginLogService.queryList(query);
        ExcelUtils.exportExcel(response, list, "登录日志");
    }

    @PreAuthorize("@perm.hasPermission('login:log$remove')")
    @Log(title = "登录日志", type = Operation.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable("ids") Long[] ids) {
        return R.result(sysLoginLogService.removeBatchByIds(List.of(ids)));
    }

    @PreAuthorize("@perm.hasPermission('login:log$remove')")
    @Log(title = "登录日志", type = Operation.CLEAN)
    @DeleteMapping("/clean")
    public R clean() {
        sysLoginLogService.clean();
        return R.success();
    }
}
